<template>
  <el-form
    ref="userForm"
    :rules="rules"
    :model="userInfo"
    label-width="120px"
    style="margin-left: 120px; margin-top: 30px"
  >
    <el-form-item label="姓名:" prop="username">
      <el-input v-model="userInfo.username" style="width: 300px" />
    </el-form-item>
    <el-form-item label="密码:" prop="password">
      <el-input
        v-model="userInfo.password"
        style="width: 300px"
        type="password"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="hSubmit">更新</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { getUserDatail } from '@/api/user'
import { saveUserDetailById } from '@/api/employees'
export default {
  data() {
    return {
      userInfo: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadUserDatail()
  },
  methods: {
    // 登录账户更新
    async doEdit() {
      try {
        const res = await saveUserDetailById(this.userInfo)
        console.log('saveUserDetailById修改成功', res)
        this.$message.success(res.message)
        // 回退到员工管理
        this.$router.back()
      } catch (error) {
        console.log(error)
      }
    },
    // 实现更新
    hSubmit() {
      this.$refs.userForm.validate(valid => {
        // 实现更新 --- 满足条件
        valid && this.doEdit()
      })
    },
    // 获取登录账户数据
    async loadUserDatail() {
      try {
        const res = await getUserDatail(this.$route.query.id)
        console.log('getUserDatail获取成功', res)
        // const { username, password } = res.data
        // this.userInfo = { username, password }
        // 保存数据
        this.userInfo = res.data
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

